package com.hades.xq.miaoshao.controller;

import com.hades.xq.miaoshao.error.BusinessException;
import com.hades.xq.miaoshao.error.EmBusinessError;
import com.hades.xq.miaoshao.response.CommonReturnType;
import com.hades.xq.miaoshao.service.OrderService;
import com.hades.xq.miaoshao.service.model.UserModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Controller("/order")
@RequestMapping("/order")
@Slf4j
@CrossOrigin(origins = "*", allowCredentials = "true", allowedHeaders = "*")
public class OrderController extends BaseController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    /**
     * 下单
     */
    @RequestMapping(value = "/createOrder", method = RequestMethod.POST, consumes = CONSUMES_TYPE_FORMED)
    @ResponseBody
    public CommonReturnType createOrder(@RequestParam(name = "itemId") Integer itemId,
                                        @RequestParam(name = "amount") Integer amount,
                                        @RequestParam(name = "promoId", required = false) Integer promoId) throws BusinessException {

        Boolean hasLogin = (Boolean) httpServletRequest.getSession().getAttribute("IS_LOGIN");
        if (hasLogin == null || !hasLogin.booleanValue()) {
            throw new BusinessException(EmBusinessError.USER_NOT_LOGIN);
        }
        UserModel userModel = (UserModel) httpServletRequest.getSession().getAttribute("LOGIN_USER");
        if (userModel == null) {
            throw new BusinessException(EmBusinessError.UNKNOW_ERROR);
        }
        orderService.createOrder(userModel.getId(), itemId, promoId, amount);

        return CommonReturnType.create(null);
    }
}
